package com.egg.logger.service;

import com.egg.auth.feign.AuthUserFeignClient;
import com.egg.auth.model.request.web.UserPagePostFeign;
import com.egg.auth.model.response.web.UserPage;
import com.egg.common.core.model.response.PageData;
import com.egg.common.core.model.response.ResponseData;
import com.egg.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * feign 调用统一处理类
 * </p>
 *
 * @author east
 * @since 2021-09-13
 */
@Slf4j
@Service
public class FeignService {


    @Autowired
    private AuthUserFeignClient authUserFeignClient;

    public Optional<UserPage> userInfo(Long userId) {
        UserPagePostFeign feign = new UserPagePostFeign();
        feign.setIds(Arrays.asList(userId));
        return userList(feign).stream().findAny();
    }

    public List<UserPage> userList(List<Long> userIds) {
        UserPagePostFeign feign = new UserPagePostFeign();
        feign.setIds(userIds);
        return userList(feign);
    }

    public List<UserPage> userList(UserPagePostFeign userPagePostFeign) {
        try {
            ResponseData<PageData<UserPage>> rd = authUserFeignClient.userPagePost(userPagePostFeign);
            if (rd.isSuccess()) {
                //Spring 返回对象 会转变为 linkedHashMap, 需要转换后使用,
                // 否则  java.util.LinkedHashMap cannot be cast to xxx
                return JsonUtil.listToList(rd.getData().getList(), UserPage.class);
            } else {
                log.error("authClient调用失败 {}", rd.getMsg());
            }
        } catch (Exception e) {
            log.error("authClient服务异常 {}", e.getMessage());
        }
        return Collections.emptyList();
    }

}
